import React, { Component } from 'react';
import { connect } from 'dva';
import { Button, Divider, Modal, Menu } from 'antd';
import { Link } from 'umi';
import TableList from '@/components/TableList';
import FilterSearch from '@/components/FilterSearch';
import EditModal from '@/components/EditModal';
import styles from './index.less';
const { confirm } = Modal;
type Props = {
  dispatch?: Function;
};

@connect(({ user }: any) => ({ user }))
class Manager<Props> extends Component {
  state = {
    loading: false,
    unitList: [], //单位列表
    selectUnit: 0, //选中的单位
  };
  table = { fetch: (e?: any) => {} };
  modal = { show: () => {} };
  modalShow = () => {};

  componentWillMount() {
    this.props
      .dispatch({
        type: '$request/post',
        payload: {
          url: '/api/structure/v1/queryAll',
          data: {
            page: 0,
            size: 20,
          },
        },
      })
      .then(({ dataList }) => {
        this.setState({
          unitList: dataList,
        });
      });
  }

  filters = [
    {
      key: 'username',
      type: 'input',
      label: '姓名',
    },
    {
      key: 'mobile',
      type: 'input',
      label: '手机号',
    },
  ];

  editFilters = [
    {
      key: 'username',
      type: 'input',
      label: '人员姓名',
      rules: [
        {
          required: true,
        },
        {
          max: 20,
          message: '不能超过20个字符',
        },
      ],
    },
    {
      key: 'mobile',
      type: 'input',
      label: '手机号',
      rules: [
        {
          max: 11,
          min: 11,
          message: '手机号限制11个字符',
        },
        { required: true },
      ],
    },
    {
      key: 'departmentUuidList',
      type: 'select',
      label: '所属部门',
      mode: 'multiple',
      asyncopt: {
        url: '/api/structure/v1/queryDepartment',
      },
      rules: [{ required: true }],
    },
    {
      key: 'jobUuidList',
      type: 'select',
      label: '岗位',
      mode: 'multiple',
      asyncopt: {
        url: '/api/job/v1/query',
      },
      rules: [{ required: true }],
    },
    {
      key: 'roleUuidList',
      type: 'select',
      label: '角色',
      mode: 'multiple',
      asyncopt: {
        url: '/api/privilege/v1/queryRole',
        params: {
          sys: false,
        },
      },
      rules: [{ required: true }],
    },
    {
      key: 'sort',
      type: 'inputnumber',
      label: '排序',
    },
  ];

  columns = [
    { title: '人员ID', dataIndex: 'id' },
    { title: '姓名', dataIndex: 'username' },
    { title: '手机号', dataIndex: 'mobile' },
    {
      title: '所属部门',
      dataIndex: 'department',
      render: (text, data) =>
        data.departmentList.map(item => item.name).join('；'),
    },
    {
      title: '岗位',
      dataIndex: 'station',
      render: (text, data) => data.jobList.map(item => item.name).join('；'),
    },
    {
      title: '角色',
      dataIndex: 'roleList',
      render: (text, data) => data.roleList.map(item => item.name).join('；'),
    },
    { title: '排序', dataIndex: 'sort' },
    {
      title: '操作',
      dataIndex: 'action', // 状态：是否锁定0：未锁定1：已锁定
      width: 325,
      render: (text: any, data: object) => (
        <span key={text}>
          <Button onClick={() => this.resetPassword(data)}>重置密码</Button>
          <Divider type="vertical" />
          <Button
            onClick={() =>
              this.modalShow({
                departmentUuidList: data.departmentList.map(item => item.uuid),
                jobUuidList: data.jobList.map(item => item.uuid),
                roleUuidList: data.roleList.map(item => item.uuid),
                ...data,
              })
            }
          >
            编辑
          </Button>
          <Divider type="vertical" />
          <Button onClick={() => this.deleteUser(data)}>删除</Button>
        </span>
      ),
    },
  ];
  /**
   * 重置密码
   */
  resetPassword(data) {
    this.props
      .dispatch({
        type: 'base/handler',
        payload: {
          type: '重置密码',
          url: '/api/account/v1/resetPassword',
          data: {
            uuid: data.uuid,
          },
        },
      })
      .then(() => {
        this.table.fetch();
      });
  }
  /**
   * 删除用户
   * @param data
   */
  deleteUser(data) {
    this.props
      .dispatch({
        type: 'base/delete',
        payload: {
          type: ` ${data.nickname} `,
          url: '/api/account/v1/deleteByUuid',
          data: {
            uuid: data.uuid,
          },
        },
      })
      .then(() => {
        this.table.fetch();
      });
  }

  /**
   * 保存
   */
  save = (data: any) => {
    if (data.id) {
      console.log('编辑');
    } else {
      console.log('add');
    }
    this.table.fetch();
  };

  menuClick = unit => {
    this.setState({
      selectUnit: unit.uuid,
    });
    this.table.fetch({
      orgUnitUuid: unit.uuid,
    });
  };
  render() {
    const { unitList } = this.state;
    return (
      <div className={styles.container}>
        <div className={styles.menu}>
          <Menu
            style={{ width: 180 }}
            defaultSelectedKeys={['home']}
            defaultOpenKeys={['sub1']}
          >
            {unitList &&
              unitList.map((unit, index) => (
                <Menu.Item key={index} onClick={() => this.menuClick(unit)}>
                  {unit.name}
                </Menu.Item>
              ))}
          </Menu>
        </div>
        <div className={styles.content}>
          <FilterSearch
            filters={this.filters}
            onSearch={(val: any) => this.table.fetch(val)}
          >
            <Button onClick={() => this.modalShow()}>添加</Button>
          </FilterSearch>
          <TableList
            post
            rowKey="id"
            onRef={c => {
              this.table = c;
            }}
            columns={this.columns}
            source="/api/account/v1/query"
          />
          <EditModal
            title="人员编辑"
            filters={this.editFilters}
            onShow={v => (this.modalShow = v)}
            onSave={() => this.table.fetch()}
            createUrl="/api/account/v1/create"
            updateUrl="/api/account/v1/update"
          />
        </div>
      </div>
    );
  }
}

export default Manager;
